import 'package:flutter/material.dart';
//导入数据
import '../model/search_data.dart';

//重构搜索类的四个方法
class SearchBarDelegate extends SearchDelegate<String>{
  // 重构搜索action方法
  @override
  List<Widget>? buildActions(BuildContext context) {
    return [
      IconButton(
          onPressed: ()=>query='',
          icon: const Icon(Icons.clear)
      )
    ];
  }

  // 重构搜索leading方法
  @override
  Widget? buildLeading(BuildContext context) {
    return IconButton(
      icon: AnimatedIcon(
        icon: AnimatedIcons.menu_arrow,
        progress: transitionAnimation,
      ),
      onPressed: () { close(context, '');},
    );
  }

  // 重构搜索结果方法
  @override
  Widget buildResults(BuildContext context) {
    final arr = searchData.where((item) => item.startsWith(query)).toList();
    if(arr.isNotEmpty) {
      return Center(
        child: SizedBox(
          width: 200.0,
          height: 200.0,
          child: Card(
            color: Colors.redAccent,
            child: Center(
              child: Text(query),
            ),
          ),
        ),
      );
    }else {
      query = '';
      return const Center(
        child: Text(
          '啊哦，没有找到相关内容哦',
          style: TextStyle(
            color: Colors.red,
            fontSize: 20.0
          ),
        ),
      );
    }
  }

  // 重构搜索中推荐部分的方法
  @override
  Widget buildSuggestions(BuildContext context) {
    final suggestionList = query.isEmpty?
    recentSuggest:searchData.where((item) => item.startsWith(query)).toList();
    return ListView.builder(
      itemCount: suggestionList.length,
      itemBuilder: (context, index){
        return ListTile(
          title: RichText(
            text: TextSpan(
              text: suggestionList[index].substring(0,query.length),
              style: const TextStyle(
                color: Colors.black,
                fontWeight: FontWeight.bold
              ),
              children: [
                TextSpan(
                  text: suggestionList[index].substring(query.length),
                  style: const TextStyle(
                    color: Colors.grey,
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}